package cn.cpf.cfets;

import com.github.cosycode.common.ext.bean.DoubleBean;
import com.github.cosycode.common.lang.WrongBranchException;
import com.google.gson.Gson;
import org.apache.commons.lang3.StringUtils;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * <b>Description : </b>
 * <p>
 * <b>created in </b> 2021/2/1
 *
 * @author CPF
 * @since
 **/
public class TxtParse {

    private static final Pattern pattern = Pattern.compile("CFETS/[A-Z]20[12]\\d—20[12]\\d");
    private static final Pattern tableTitle = Pattern.compile("表\\d{1,3} \\w+ IMIX报文标准");
    private static final Pattern tableTitleHandle = Pattern.compile("域号\\s+域名 取值 说明");
    private static final Pattern rowContent = Pattern.compile("\\d{1,5} [A-Za-z]+ \\w+ \\S+");

    private static final String SPACE_STR = " ";

    public static List<ImixTable> parse(List<String> string) {
        // 0: no, 1 : title, 2: head, 3: body, 4: tail;
        int tableFlag = 0;
        int notDisposeLine = 0;
        int columnsCount = 0;
        List<ImixTable> list = new ArrayList<>();
        ImixTable table = null;
        HistoryStack<String> historyQueue = new HistoryStack<>(20);
        for (String s : string) {
            s = s.trim();
            historyQueue.add(s);
            if (pattern.matcher(s).matches()) {
                notDisposeLine = 0;
                continue;
            }
            switch (tableFlag) {
                case 0:
                    if (tableTitle.matcher(s).matches()) {
                        table = new ImixTable();
                        final String[] s1 = s.split(SPACE_STR);
                        assert s1.length == 3;
                        table.setTableIdx(s1[0]);
                        table.setTableName(s1[1]);
                        tableFlag = 1;
                        notDisposeLine = 0;
                        break;
                    }
                    notDisposeLine ++;
                    break;
                case 1:
                    if (tableTitleHandle.matcher(s).matches()){
                        assert s.length() >= 11;
                        columnsCount = s.length() - 11 + 4;
                        notDisposeLine = 0;
                        break;
                    }
                    if ("StandardHeader".equals(s)) {
                        tableFlag = 2;
                        notDisposeLine = 0;
                        break;
                    }
                    notDisposeLine ++;
                    break;
                case 2: {
                    assert table != null;
                    final String[] split = s.split(SPACE_STR);
                    if ("MessageBody".equals(s)) {
                        while (notDisposeLine > 0) {
                            table.appendHandleComment(historyQueue.prev(notDisposeLine--));
                        }
                        tableFlag = 3;
                        notDisposeLine = 0;
                        break;
                    }
                    final DoubleBean<FieldRowMatch, FieldRow> fileRowCombine = FieldRow.checkAndComposeFieldRow(split);
                    final FieldRowMatch rowMatch = fileRowCombine.getO1();
                    switch (rowMatch) {
                        case NO_MATCHED:
                            // 当前行未匹配成功, 可能情况
                            if (notDisposeLine == 0) {
                                // 1. 上一行匹配成功
                                // 将当前行是上一个匹配成功的尾行
                                table.appendHandleComment(s);
                                break;
                            }
                            assert notDisposeLine > 0;
                            // 2. 上一行未匹配成功 ==> 将上一行或几行合并再次匹配
                            final String join = StringUtils.join(historyQueue.prevList(notDisposeLine), "") + s;
                            final String[] tempSplit = join.split(SPACE_STR);
                            final DoubleBean<FieldRowMatch, FieldRow> rowDoubleBean = FieldRow.checkAndComposeFieldRow(tempSplit);
                            if (rowDoubleBean.getO1().equals(FieldRowMatch.CHECK_SUCCESS)){
                                table.addStandardHeaderRow(rowDoubleBean.getO2());
                                notDisposeLine = 0;
                            } else {
                                notDisposeLine++;
                            }
                            break;
                        case FIELD_MATCHED:
                        case FIELD_NAME_MATCHED:
                        case VAL_MATCHED:
                            // 当前行可能未完成, 下一行可能是当前行的尾行
                            assert notDisposeLine == 0;
                            notDisposeLine ++;
                            break;
                        case COMMENT_MATCHED:
                            throw new WrongBranchException();
                        case CHECK_SUCCESS:
                            assert notDisposeLine == 0;
                            table.addStandardHeaderRow(fileRowCombine.getO2());
                            break;
                    }
                    break;
                }
                case 3: {
                    assert table != null;
                    if ("StandardTrailer".equals(s)) {
                        while (notDisposeLine > 0) {
                            table.appendBodyComment(historyQueue.prev(notDisposeLine--));
                        }
                        tableFlag = 4;
                        notDisposeLine = 0;
                        break;
                    }
                    final String[] split = s.split(SPACE_STR);
                    final DoubleBean<FieldRowMatch, FieldRow> fileRowCombine = FieldRow.checkAndComposeFieldRow(split);
                    final FieldRowMatch rowMatch = fileRowCombine.getO1();
                    switch (rowMatch) {
                        case NO_MATCHED:
                            // 当前行未匹配成功, 可能情况
                            if (notDisposeLine == 0) {
                                // 1. 上一行匹配成功
                                // 将当前行是上一个匹配成功的尾行
                                table.appendHandleComment(s);
                                break;
                            }
                            assert notDisposeLine > 0;
                            // 2. 上一行未匹配成功 ==> 将上一行或几行合并再次匹配
                            final String join = StringUtils.join(historyQueue.prevList(notDisposeLine), "") + s;
                            final String[] tempSplit = join.split(SPACE_STR);
                            final DoubleBean<FieldRowMatch, FieldRow> rowDoubleBean = FieldRow.checkAndComposeFieldRow(tempSplit);
                            if (rowDoubleBean.getO1().equals(FieldRowMatch.CHECK_SUCCESS)){
                                table.addStandardHeaderRow(rowDoubleBean.getO2());
                                notDisposeLine = 0;
                            } else {
                                notDisposeLine++;
                            }
                            break;
                        case FIELD_MATCHED:
                        case FIELD_NAME_MATCHED:
                        case VAL_MATCHED:
                            // 当前行可能未完成, 下一行可能是当前行的尾行
                            assert notDisposeLine == 0;
                            notDisposeLine ++;
                            break;
                        case COMMENT_MATCHED:
                            throw new WrongBranchException();
                        case CHECK_SUCCESS:
                            assert notDisposeLine == 0;
                            table.addStandardHeaderRow(fileRowCombine.getO2());
                            break;
                    }
                    break;
                }
                case 4:
                    tableFlag = 0;
                    list.add(table);
                    break;
            }

        }
        return list;
    }


    public static String getFirstString(String s) {
        final int i = s.indexOf(" ");
        return s.substring(0, i);
    }



    public static void main(String[] args)  {
        final String file = "D:\\Users\\CPF\\Desktop\\FMBS\\resources\\CFETS 开发指引\\接口开发指引-本币\\新平台本币交易接口\\PDFTextStripper.txt";
        List<String> collect = null;
        try (BufferedReader reader = new BufferedReader(new FileReader(file))){
            collect = reader.lines().collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        final List<ImixTable> parse = parse(collect);
        parse.forEach(it -> {
            System.out.println(new Gson().toJson(it));
        });

    }

}
